package com.lewis.realm;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.lewis.entry.User;
import com.lewis.entry.UserRole;
import com.lewis.mapper.UserMapper;
import com.lewis.mapper.UserVoMapper;


public class CustomeRealm extends AuthorizingRealm{
	
	@Resource
	private UserMapper userMapper;
	
	@Resource
	private UserVoMapper userVoMapper;
	
    /**
     * permission  config
     */
	@Override
	public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		
		
		
		String username=(String)principals.getPrimaryPrincipal();
		//get roles and permission from cache or datebase
		Set<UserRole> roles= userVoMapper.getUserVo(username).getRoles();
		//roles集合
		Set<String> roleSet=new HashSet<String>();
		for (UserRole userRole : roles) {
			roleSet.add(userRole.getRole());
		}
		//permission 集合
		Set<String>permsSet=null;
		try {
			permsSet=userMapper.getPermis(username).getPerms();
		} catch (Exception e) {
			e.printStackTrace();
		}
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(roleSet);
		authorizationInfo.setStringPermissions(permsSet);
		System.out.println("************************************开始授权*************************************");
		System.out.println("roles:"+roleSet);
		System.out.println("perms:"+permsSet);
		return authorizationInfo;
	}
	
	/**
	 * 
	 */
	@Override
	public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		SimpleAuthenticationInfo authenticationInfo=null;
		try {
			//从前端提交上来的username
			String username=(String)token.getPrincipal();
			//从数据库获取salt和password
		    User u = userMapper.getUser(username).get(0);
			String password=u.getPassword();
			String salt=u.getSalt();
			authenticationInfo = new SimpleAuthenticationInfo(username,password,super.getName());		
			authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(salt));
			//ok
			System.out.println("username=:"+username+"---password=:"+password+"---salt=:"+salt);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return authenticationInfo;
	}

}
